package com.tange.ai.core.demo.ui.notifications;

import android.annotation.SuppressLint;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.bumptech.glide.Glide;
import com.bumptech.glide.load.resource.bitmap.RoundedCorners;
import com.bumptech.glide.request.RequestOptions;
import com.google.common.reflect.TypeToken;
import com.google.gson.JsonArray;
import com.google.gson.JsonObject;
import com.tange.ai.core.demo.R;
import com.tange.ai.core.demo.databinding.FragmentNotificationsBinding;
import com.tange.ai.core.demo.ui.home.HomeFragment;
import com.tange.base.toolkit.StringUtils;
import com.tange.core.backend.service.request.Http;
import com.tange.core.backend.service.request.HttpResponse;
import com.tange.core.backend.service.response.RxResponse;
import com.tange.core.data.structure.Device;
import com.tange.module.camera.password.DeviceBasicQuery;
import com.tange.module.camera.query.DeviceCoreQuery;
import com.tg.appcommon.android.TGLog;
import com.tg.data.http.entity.DeviceListResponse;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;
import io.reactivex.schedulers.Schedulers;

/**
 * 展示名下所有设备的 消息事件
 */
public class NotificationsFragment extends Fragment {

    private static final String TAG = "HomeFragment";

    private static final String CLOUD_API_DEVICE_LIST = "/app/v1/device/list";
    private static final String PARAM_PAGE_INDEX = "page";
    private static final String PARAM_PAGE_LIMIT = "limit";

    private FragmentNotificationsBinding binding;

    private ListAdapter listAdapter;

    private Disposable disposable;

    public View onCreateView(@NonNull LayoutInflater inflater,
                             ViewGroup container, Bundle savedInstanceState) {

        binding = FragmentNotificationsBinding.inflate(inflater, container, false);
        View root = binding.getRoot();

        listAdapter = new ListAdapter();
        binding.apList.setLayoutManager(new LinearLayoutManager(getActivity(), LinearLayoutManager.VERTICAL, false));
        binding.apList.setAdapter(listAdapter);

        return root;
    }

    @Override
    public void onResume() {
        super.onResume();
        refreshDeviceList();
    }

    private void refreshDeviceList() {

        if (disposable != null && !disposable.isDisposed()) {
            disposable.dispose();
        }

        disposable = DeviceCoreQuery.INSTANCE.queryPage(1, 100, "").subscribe(devices -> {
            if (devices != null && devices.size() > 0) {
                requestMessageFilters(devices);
                binding.emptyView.setVisibility(View.GONE);
            } else {
                binding.emptyView.setVisibility(View.VISIBLE);
            }
        }, throwable -> {
            binding.loading.setVisibility(View.GONE);
            Toast.makeText(getActivity(), "请求失败：" + throwable, Toast.LENGTH_LONG).show();
            TGLog.i(TAG, "[refreshDeviceList] throwable = " + throwable);
        });
    }

    @SuppressLint("CheckResult")
    private void requestMessageFilters(List<Device> deviceItems)  {
        String uuid = "";
        for (Device item : deviceItems) {
            if (!StringUtils.isEmpty(uuid)){
                uuid += ",";
            }
            uuid += item.getUuid();
        }

        Http.INSTANCE.create()
                .path("/app/v1/alarm_msg/filter")
                .param("uuid", uuid)
                .post()
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(response -> {
                    if (response.isSuccess()) {
                        List<MessageFilter> messageFilters = response.parse(new TypeToken<List<MessageFilter>>(){}.getType());
                        requestLast7DaysMessages(deviceItems, messageFilters);
                    }
                });


    }

    private void requestLast7DaysMessages(List<Device> deviceItems, List<MessageFilter> content) {
        String deviceIds = "";
        for (Device item : deviceItems) {
            if (item.getId() > 0){
                deviceIds += ",";
            }
            deviceIds += item.getId();
        }

        HashMap<String, String> map = new HashMap<>();

        map.put("device_id", deviceIds);

        map.put("start_timestamp", String.valueOf((System.currentTimeMillis() - 7 * 24 * 60 * 60 * 1000) / 1000 ));
        map.put("end_timestamp", String.valueOf(System.currentTimeMillis() / 1000));
        map.put("page", String.valueOf(1));
        map.put("limit", String.valueOf(100));

        JSONObject object = JSON.parseObject(JSON.toJSONString(map));

        ArrayList<String> list = new ArrayList<>();

        for (MessageFilter alertMessageFilterBean : content) {
            list.add(alertMessageFilterBean.tag);
        }

        object.put("message_type", list);

        Http.INSTANCE.create().path("/app/user/query/alarm_msg").params(map).post()
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                        .subscribe(new Observer<HttpResponse>() {
                            @Override
                            public void onSubscribe(Disposable d) {

                            }

                            @Override
                            public void onNext(HttpResponse response) {
                                binding.loading.setVisibility(View.GONE);

                                if (response.isSuccess()) {
                                    MessageList messageList = response.parse(MessageList.class);
                                    if (messageList != null && messageList.items != null && messageList.items.size() > 0) {
                                        binding.emptyView.setVisibility(View.GONE);
                                        listAdapter.refresh(messageList.items);
                                    }
                                }
                            }

                            @Override
                            public void onError(Throwable e) {
                                binding.loading.setVisibility(View.GONE);
                            }

                            @Override
                            public void onComplete() {

                            }
                        });
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        binding = null;
    }


    public class ListAdapter extends RecyclerView.Adapter<ViewHolder> {

        private List<MessageList.Message> apList = new ArrayList<>();

        public void refresh(List<MessageList.Message> list) {
            this.apList.clear();
            this.apList.addAll(list);
            notifyDataSetChanged();
        }

        @Override
        public ViewHolder onCreateViewHolder(ViewGroup viewGroup, int viewType) {
            View view = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.item_msg_list, viewGroup, false);
            return new ViewHolder(view);
        }

        @Override
        public void onBindViewHolder(ViewHolder viewHolder, final int position) {
            final MessageList.Message item = apList.get(position);
            viewHolder.name.setText(item.messageType);
            viewHolder.time.setText(item.deviceName);
            viewHolder.offline.setText(item.time);
            Glide.with(getActivity())
                    .load(item.coverUrl)
                    .apply(RequestOptions.bitmapTransform(new RoundedCorners(25)))
                    .into(viewHolder.cover);
        }

        @Override
        public int getItemCount() {
            return apList.size();
        }
    }

    public static class ViewHolder extends RecyclerView.ViewHolder {

        public final ImageView cover;
        public final TextView name;
        public final TextView offline;
        public final TextView time;

        public ViewHolder(View view) {
            super(view);
            cover = view.findViewById(R.id.cover);
            name = view.findViewById(R.id.name);
            time = view.findViewById(R.id.time);
            offline = view.findViewById(R.id.online);
        }
    }
}